﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESystem.Extensions;
using System.Diagnostics;

namespace ENG.PSSAirbusSoundExtender
{
  public partial class FrmMain : Form
  {    

    public FrmMain()
    {
      Program.OverheadClick += new Program.ClickHandler(Program_OverheadClick);
      InitializeComponent();
    }

    void Program_OverheadClick(Point point)
    {
      PSS.ProceedClick(point);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      this.Text = Application.ProductName + " " + Application.ProductVersion.ToString();

      if (!string.IsNullOrEmpty(Properties.Settings.Default.CurrentFile))
      {
        Exception ex;
        var s = LoadRectangles(Properties.Settings.Default.CurrentFile, out ex);
        if (ex != null)
        {
          MessageBox.Show("Last used file " + Properties.Settings.Default.CurrentFile +
            " cannot be loaded. Reason: " + ex.Message);
        }
        else
        {
          SetSystems(s);
        }
      }
    }

    private void SetSystems(List<ASystem> s)
    {
      bool isOdd = false;
      PSS.ShutDown();
      PSS.StartUp(s);

      pnlFlow.Controls.Clear();
      foreach (var fItem in s)
      {
        var sc = CreateSystemPanel(fItem);

        if (isOdd)
          sc.BackColor = System.Drawing.SystemColors.ControlDark;

        isOdd = !isOdd;

        pnlFlow.Controls.Add(sc);
      } // foreach (var fItem in systems)
    }

    private SystemControl CreateSystemPanel(ASystem s)
    {
      SystemControl sc = new SystemControl();
      sc.Associate(s);

      sc.ChangeRequest += new SystemControl.ASystemDelegate(sc_ChangeRequest);
      sc.SwitchRequest += new SystemControl.ASystemDelegate(sc_SwitchRequest);
      sc.DeleteRequest += new SystemControl.ASystemDelegate(sc_DeleteRequest);

      return sc;
    }

    void sc_DeleteRequest(SystemControl sender, ASystem s)
    {
      var ss = PSS.GetSystems();
      ss.Remove(s);

      PSS.StartUp(ss);
      SetSystems(ss);

    }

    void sc_SwitchRequest(SystemControl sender, ASystem s)
    {
      PSS.SwitchSystem(s);      
    }

    void sc_ChangeRequest(SystemControl sender, ASystem s)
    {
      FrmSystemEdit f = new FrmSystemEdit();

      if (s.IsOn)
        s.Switch();

      f.SetBy(s);
      f.ShowDialog();

      if (f.DialogResult == DialogResult.OK)
      {
        f.GetTo(s);

        s.Reset();
      }
    }

    private List<ASystem> CreateDefaultSystems()
    {
      List<ASystem> ret = new List<ASystem>();
      ASystem s;

      s = new ASystem()
      {
        Name = "Battery left", 
         DefaultIsOn=false, 
         IsOn= false, 
         GoVoice = null, 
         IsBattery = true, 
         StartButton = new EButton() { Name="BAT 1", Rectangle=new Rectangle()},
         StartVoice = null, 
         MinBatteryCountToRun = 0
      };
      s.StopButton = s.StartButton;
        ret.Add(s);

        s = new ASystem()
        {
          Name = "Battery right",
          DefaultIsOn = false,
          IsOn = false,
          GoVoice = null,
          IsBattery = true,
          StartButton = new EButton() { Name = "BAT 2", Rectangle = new Rectangle() },
          StartVoice = null,
          MinBatteryCountToRun = 0
        };
        s.StopButton = s.StartButton;
        ret.Add(s);

        s = new ASystem()
        {
          Name = "APU",
          DefaultIsOn = false,
          IsOn = false,
          GoVoice = null,
          IsBattery = false,
          StartButton = new EButton() { Name = "APU START", Rectangle = new Rectangle() },
          StartVoice = null,
          MinBatteryCountToRun = 1
        };
        s.StopButton = new EButton() { Name = "APU MASTER SWITCH", Rectangle = new Rectangle() };
        ret.Add(s);

        s = new ASystem()
        {
          Name = "Pack 1",
          DefaultIsOn = true,
          IsOn = false,
          GoVoice = null,
          IsBattery = false,
          StartButton = new EButton() { Name = "PACK 1", Rectangle = new Rectangle() },
          StartVoice = null,
          MinBatteryCountToRun = 2
        };
        s.StopButton = s.StartButton;
        ret.Add(s);

        s = new ASystem()
        {
          Name = "Pack 2",
          DefaultIsOn = true,
          IsOn = false,
          GoVoice = null,
          IsBattery = false,
          StartButton = new EButton() { Name = "PACK 2", Rectangle = new Rectangle() },
          StartVoice = null,
          MinBatteryCountToRun = 2
        };
        s.StopButton = s.StartButton;
        ret.Add(s);

      return ret;
    }

    private static string GetFileName()
    {
      string fileName = System.IO.Path.Combine(
       Application.LocalUserAppDataPath, "systems.xml");
      return fileName;
    }
    public List<ASystem> LoadRectangles(string fileName, out Exception error)
    {
      List<ASystem> ret = new List<ASystem>();
      System.IO.FileStream fs = null;

      try
      {
        fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open);
        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(ret.GetType());

        ret = (List<ASystem>)ser.Deserialize(fs);

        fs.Close();

        error = null;
      }
      catch (Exception ex)
      {
        error = ex;
        if (fs != null) fs.Close();
        ret = null;
      }

      return ret;

    }

    public void SaveRectangles(List<ASystem> items, string fileName, out Exception err)
    {
      string tempName = System.IO.Path.GetTempFileName();
      List<ASystem> ret = new List<ASystem>();
      System.IO.FileStream fs = null;

      try
      {
        fs = new System.IO.FileStream(tempName, System.IO.FileMode.Truncate);
        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(ret.GetType());

        ser.Serialize(fs, items);

        fs.Close();

        System.IO.File.Copy(tempName, fileName, true);
        System.IO.File.Delete(tempName);

        err = null;
      }
      catch (Exception ex)
      {
        if (fs != null) fs.Close();
        err = ex;
      }

    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
      Application.UseWaitCursor = true;

      PSS.ShutDown();

      Properties.Settings.Default.Save();
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void openConfigFileToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if (string.IsNullOrEmpty(Properties.Settings.Default.CurrentFile))
        MessageBox.Show("No file opened.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
      else
      {
        Process p = new Process();
        p.StartInfo.Arguments = Properties.Settings.Default.CurrentFile;
        p.StartInfo.FileName = "notepad";

        p.Start();
      }
    }

    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
      StringBuilder s = new StringBuilder();

      s.AppendLine(Application.ProductName);
      s.AppendLine(Application.ProductVersion.ToString());
      s.AppendLine();
      s.AppendLine(Application.CompanyName);
      s.AppendLine("http://pssase.codeplex.com/");

      MessageBox.Show(
        s.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);

    }

    private void viewconsoleToolStripMenuItem_Click(object sender, EventArgs e)
    {
      FrmConsole f = new FrmConsole();
      f.Show();
    }

    private void defaultToolStripMenuItem_Click(object sender, EventArgs e)
    {
      List<ASystem> s = CreateDefaultSystems();
      SetSystems(s);
    }

    private void newToolStripMenuItem_Click(object sender, EventArgs e)
    {
      List<ASystem> s = new List<ASystem>();
      SetSystems(s);
    }

    private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if (string.IsNullOrEmpty(Properties.Settings.Default.CurrentFile))
        ofd.InitialDirectory = Application.UserAppDataPath;

      if (ofd.ShowDialog() != DialogResult.OK)
        return;

      string f = ofd.FileName;
      Exception ex;

      List<ASystem> s = LoadRectangles(f, out ex);

      if (ex != null)
      {
        MessageBox.Show("Unable to load data from " + GetFileName() + ". Reason: " + ex.Message +
          ". File not loaded.");
      }
      else
      {
        SetSystems(s);
        Properties.Settings.Default.CurrentFile = f;
      }
    }

    private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(Properties.Settings.Default.CurrentFile))
        sfd.FileName = Properties.Settings.Default.CurrentFile;
      else
        sfd.InitialDirectory = Application.UserAppDataPath;

      if (sfd.ShowDialog() != DialogResult.OK)
        return;

      List<ASystem> s = PSS.GetSystems();
      Exception ex;

      SaveRectangles(s, sfd.FileName, out ex);

      if (ex != null)
      {
        MessageBox.Show("Unable to save data to " + GetFileName() + ". Reason: " + ex.Message +
          ". File not saved.");
      }
      else
      {
        Properties.Settings.Default.CurrentFile = sfd.FileName;
        MessageBox.Show("Saved.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
      }
    }

    private void addNewSystemToolStripMenuItem_Click(object sender, EventArgs e)
    {
      string systemName =
        ESystem.Forms.InputBox.ShowDialog("Name of the system...", "Enter name for the new system:", "System A");

      if (systemName == null)
        return;

      ASystem s = new ASystem(systemName, false, new EButton(), "");

      var oldSystems = PSS.GetSystems();

      oldSystems.Add(s);

      SetSystems(oldSystems);
    }

    private void resetAllSystemsToolStripMenuItem_Click(object sender, EventArgs e)
    {
    }
  }
}
